import socket from 'ws'
import system from "./system";
import eventEmit from './emitEvent';
// 使用单列模式
class websocketIo {
    public static instance; // 实列对象
    public socketObj:any = null; // pc端通信对象
    static get getInstance() {
        if (!this.instance) {
            this.instance = new websocketIo()
        }
        return this.instance
    }
    // 连接对象
    connection(port:number) {
         let socketObj = new socket.Server({port})
         socketObj.on("connection",(client:any,upgradeReq) => {
            this.socketObj = client
            console.log("设备连接成功")
            client.on("close", () => {
                console.log("断开连接")
                this.socketObj = null
            })
             // 接收数据
             client.on("message", async (msg: string) => {
                let data:Record<string,any> = JSON.parse(msg.toString())
                if (data.action === 'renderSystemInfo') {
                    client.send(JSON.stringify({
                        diskInfo: await system.getDiskInfo(),
                        memInfo: await system.getMemInfo(),
                        cpuInfo: await system.getCpuInfo()
                    }))
                } else if (data.action === 'changeVal') {
                    // 改变阈值
                    let errorVal: string | number = data.errorVal //报警值
                    let module_id: number = data.module_id // 模块编号
                    let type = data.type_id // 阈值类型 1~5 紫外、红外、温度、湿度、压力
                    console.log(errorVal,module_id,type)
                    // 改变服务端的阈值
                    eventEmit.changeVal(module_id,type,errorVal)
                } else if (data.action === 'get_val') {
                    // 获取阈值
                    client.send(JSON.stringify({
                        action: 'get_val',
                        data: eventEmit.settingData
                    }))
                }
             })
        })
    }
}

export default websocketIo
